package com.tian.authen.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.tian.authen.dao.UserDao;
import com.tian.authen.entity.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.tian.authen.entity.table.UserTableDef.USER;
/**
 *
 * <pre>
 *     通过查询数据的用户信息，来校验账户信息。
 * </pre>
 *
 * @author zhumengping
 * @title: CustomUserDetailServiceImpl
 * @projectName zhump-cloud
 * @date 2023/8/10 9:39
 */
@Log4j2
@Service
public class CustomUserDetailServiceImpl implements UserDetailsService {


    @Autowired
    private UserDao dao;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("[CustomUserDetailServiceImpl()]check user data:{}",username);
        QueryWrapper where = QueryWrapper.create()
                .select(USER.ALL_COLUMNS)
                .where(USER.USER_NAME.eq(username));
        List<User> users = dao.selectListByQuery(where);
        if (null == users || users.isEmpty()) {
            throw new UsernameNotFoundException(username);
        }
        User user = users.get(0);
        return new org.springframework.security.core.userdetails.User(
                user.getUser_name(),
                user.getPass_word(),
                AuthorityUtils.createAuthorityList("USER"));
    }


}
